package cn.edu.sjtu.tooling.util;

import cn.edu.sjtu.tooling.domain.Task;
import cn.edu.sjtu.tooling.enums.ECNStateEnum;
import cn.edu.sjtu.tooling.enums.TaskStateEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@Data
public class TaskExecuteUtil {

  private ECNStateEnum deviceStatus = ECNStateEnum.READY;

  private Task currentTask;

  @Value("${tooling.executeTime}")
  private long executeTime;

  @Value("${tooling.doneTime}")
  private long doneTime;

  private Map<String, Task> taskPool = new ConcurrentHashMap<>();

  private void beginTask(Task task) {
    this.currentTask = task;
    // 让设备执行
    this.deviceStatus = ECNStateEnum.BUSY;
    String key = task.getProcessId().concat(task.getTaskId());
    Task cur = taskPool.get(key);
    cur.setStartTime(new Date());
    cur.setStatus(TaskStateEnum.EXECUTING);
  }

  private void finishTask() {
    // 设备状态转为空闲
    this.deviceStatus = ECNStateEnum.IDLE;
    // 任务状态变为done
    currentTask.setStatus(TaskStateEnum.DONE);
    currentTask.setEndTime(new Date());
    this.currentTask = null;
  }

  private void readyTask() {
    this.deviceStatus = ECNStateEnum.READY;
  }

  @Async
  public void executeTask(Task task) {
    beginTask(task);
    try {
      Thread.sleep(executeTime);
    } catch (InterruptedException e) {
      log.error("线程休眠中断，历史执行任务有: {}, {}", taskPool, e.getMessage());
    }
    finishTask();
    try {
      Thread.sleep(doneTime);
    } catch (InterruptedException e) {
      log.error("线程休眠中断，历史执行任务有: {}, {}", taskPool, e.getMessage());
    }
    readyTask();
  }
}
